﻿using System;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using SJKP.PDFConversion.Service;

namespace SJKP.PDFConversion.ADMIN.SJKP.OCR
{
    /// <summary>
    /// Administrative page for managing the service application.
    /// </summary>
    public partial class Manage : GlobalAdminPageBase 
    {
        private const string adminServiceapplicationsPage = "/_admin/ServiceApplications.aspx";

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!Page.IsPostBack)
            {
                dvdList.SelectedValue = ServiceApplication.PdfConverterType;
            }

        }

        protected void OkButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            ServiceApplication.PdfConverterType = dvdList.SelectedValue;
            ServiceApplication.Update();
            RedirectOnOK();
        }

        private OCRServiceApplication ServiceApplication
        {
            get
            {
                Guid guid = new Guid(Request.QueryString["id"]);
                if(Guid.Empty == guid)
                {
                    throw new InvalidOperationException("Query string parameter 'id' not parsable as guid");
                }

                OCRServiceApplication serviceApp = SPFarm.Local.GetObject(guid) as OCRServiceApplication;
                if (serviceApp == null)
                {
                    throw new InvalidOperationException("Service Application couldn't be found");
                }
                return serviceApp;
            }
        }

        public override string PageToRedirectOnCancel
        {
            get
            {
                return adminServiceapplicationsPage;
            }
        }

        public override string PageToRedirectOnOK
        {
            get
            {
                return adminServiceapplicationsPage;
            }
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            base.RedirectToApplicationManagementPage();
        }
    }
}
